package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.dto.RequestParamsDto;
import cn.itcast.hotel.entity.dsl.HotelDSL;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.entity.Hotel;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.vo.PageResultVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.lucene.search.BooleanQuery;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageResultVo search(RequestParamsDto params) {
        // 1. 准备 request
        SearchRequest request = new SearchRequest("hotel");

        // 2. 准备 DSL
        // 2.1 构建BoolQuery
        buildBasicQuery(params, request);

        // 2.2 分页
        int page = params.getPage();
        int size = params.getSize();
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 10;
        }
        request.source().from((page - 1) * size).size(size);

        // 2.3 地理排序
        String location = params.getLocation();
        if (StringUtils.hasLength(location)) {
            request.source().sort(SortBuilders.geoDistanceSort(
                    "location", new GeoPoint(location))
                    .order(SortOrder.ASC)
                    .unit(DistanceUnit.KILOMETERS));
        }

        // 3. 发送请求, 得到响应
        SearchResponse response;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
            // 4. 解析响应
            return handelResponse(response);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 聚合信息, 返回给页面
     */
    @Override
    public Map<String, List<String>> filter(RequestParamsDto params) {

        Map<String, List<String>> map = new HashMap<>();

        // 准备请求
        SearchRequest request = new SearchRequest("hotel");

        // 准备 query, 过滤条件
        buildBasicQuery(params, request);

        // 设置 size
        request.source().size(0);
        // 聚合
        buildAggregation(request);

        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 解析结果
            Aggregations aggregations = response.getAggregations();
            // 根据名称获取品牌结果
            List<String> brandList = getAggListByName(aggregations, "brandApp");
            List<String> cityList = getAggListByName(aggregations, "cityApp");
            List<String> starList = getAggListByName(aggregations, "starApp");

            map.put("brand", brandList);
            map.put("city", cityList);
            map.put("starName", starList);

            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void buildAggregation(SearchRequest request) {
        request.source()
                .aggregation(AggregationBuilders
                        .terms("brandApp")
                        .field("brand")
                        .size(10));
        request.source()
                .aggregation(AggregationBuilders
                        .terms("cityApp")
                        .field("city")
                        .size(10));
        request.source()
                .aggregation(AggregationBuilders
                        .terms("starApp")
                        .field("starName")
                        .size(10));
    }


    /**
     * 通过聚合名字, 获取聚合结果
     */
    private List<String> getAggListByName(Aggregations aggregations, String name) {
        Terms terms = aggregations.get(name);
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);

        }
        return list;
    }


    private void buildBasicQuery(RequestParamsDto params, SearchRequest request) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // must: 关键字搜索
        String key = params.getKey();
        if (StringUtils.hasLength(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            // 搜索框为空
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 条件过滤
        // 1. 城市
        String city = params.getCity();
        if (StringUtils.hasLength(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        // 2. 品牌
        String brand = params.getBrand();
        if (StringUtils.hasLength(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        // 3. 星级
        String starName = params.getStarName();
        if (StringUtils.hasLength(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName", starName));
        }
        // 4. 价格
        BigDecimal minPrice = params.getMinPrice();
        BigDecimal maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(minPrice).lte(maxPrice));
        }

        // 算分控制
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                // 原始查询, 相关性算分的查询
                boolQuery,
                // function score 数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // function score 数组的一个数组: 包含过滤条件 和 算分函数
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                // 过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                // 算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });

        // 算分条件: +10
        functionScoreQueryBuilder.boostMode(CombineFunction.SUM);

        request.source().query(functionScoreQueryBuilder);
    }


    /**
     *  处理 response 的函数
     */
    private PageResultVo handelResponse(SearchResponse response) {

        // 数据解析(对照 DSL 语句)
        // 1. 拿到源数据
        SearchHits responseHits = response.getHits();
        // 2. 拿到查询总条数
        long total = responseHits.getTotalHits().value;
        // 3. 拿到数据数组
        SearchHit[] searchHits = responseHits.getHits();
        // 4. 遍历拿到每个 source
        List<HotelDSL> hotels = new ArrayList<>();
        for (SearchHit documentFields : searchHits) {
            // 4.1 拿到 source
            String source = documentFields.getSourceAsString();
            // 4.2 打印结果 (或其他处理)
            HotelDSL hotelDSL;
            try {
                hotelDSL = objectMapper.readValue(source, HotelDSL.class);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            // 4.3 获取高亮结果集
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();

            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    String name = highlightField.getFragments()[0].string();
                    hotelDSL.setName(name);
                }
            }
            // 获取(地理)排序值, 仅仅进行地理排序的时候, sort 的值才是距离, 才正确.4
            Object[] sortValues = documentFields.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDSL.setDistance(sortValue);
            }

            System.out.println(hotelDSL);
            hotels.add(hotelDSL);
        }
        System.out.println("一共查询到条数: " + total);

        return new PageResultVo(total, hotels);
    }
}
